package com.tamtamy.jtta.data.xml;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.tamtamy.jtta.data.NetworkList;
import com.tamtamy.jtta.exception.NoResultException;
import com.tamtamy.jtta.exception.ParsingException;
import com.tamtamy.jtta.utility.XMLUtility;

public class XMLNetworkList extends NetworkList {
	
	private static final long serialVersionUID = -5781076195222720936L;
	
	private static final String KCLNETWORK = "it.reply.tt.rest.entity.KcLNetwork";
	
	public XMLNetworkList(Document xmlDocument) throws NoResultException, ParsingException {
		super();
		NodeList networkNodeList = xmlDocument.getElementsByTagName(KCLNETWORK);
		if (networkNodeList == null || networkNodeList.getLength()==0){
			throw new NoResultException("No " + KCLNETWORK + " element found");
		}
		for (int i = 0; i < networkNodeList.getLength(); i++) {
			Node networkNode = networkNodeList.item(i);
			try {
				Document networkDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
				networkDocument.appendChild(networkDocument.importNode(networkNode, true));
				this.add(new XMLNetwork(networkDocument)); 
			} catch (ParserConfigurationException parserConfigurationException) {
				throw new ParsingException("Error parsing " + KCLNETWORK + " element : " + parserConfigurationException.getMessage());
			}   
		}	
		setTotal(XMLUtility.getInt(xmlDocument, "total")); 
	}
}
